<template>
  <el-button :disabled="disabled" @click="addTimeQuantum(null)">添加时段</el-button>
  <el-form ref="quietTimeQuantumFormRef" :model="timeQuantumForm" :rules="timeQuantumRules">
    <el-form-item v-for="(key) in Object.keys(timeQuantumForm)" :key="key" :prop="key">
      <TimeQuantum :isDel="Object.keys(timeQuantumForm).length > 1" v-model="timeQuantumForm[key]" @change="timeChange" @del="deleteItem($event, key)" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch, computed, nextTick, onMounted, defineAsyncComponent } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'

  let TimeQuantum = ref<any>(null)

  const quietTimeQuantumFormRef = ref<FormInstance>()
  const validateTime = (rule: any, value: any, callback: any) => {
    if (value.some((ite:string) => !ite)) {
      callback(new Error('请选择完整的规则时段'))
    } else {
      const flag = validateRepeat(value) as boolean
      if(flag){
        callback(new Error('请勿选择相同时段！'))
      }else{
        callback()
      }
    }
  }
  const validateRepeat = (arr: string[]):boolean=>{
    let flag:number = 0
    Reflect.ownKeys(timeQuantumForm).forEach(key=>{
      if(timeQuantumForm[key].toString() === arr.toString()){
        flag++
      }
    })
    return flag > 1
  }

  const rule = reactive<any>([
    { required: true, message: '请选择规则时段', trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ])

  const timeQuantumForm = reactive({})
  const timeQuantumRules = reactive<FormRules>({})

  type Props = {
    modelValue: Array<Array<string>>|any
  }
  const props = withDefaults(defineProps<Props>(), {
    modelValue: []
  })

  let disabled = ref<boolean>(false)
  let maxNum = ref<number>(20)   // 超时规则最多20条
  const emit = defineEmits(['update:modelValue'])

  const timeChange = (flag:boolean)=>{
    if(flag){
      emit('update:modelValue', getParamsArr())
    }
  }

  const getParamsArr = () => {
    return Reflect.ownKeys(timeQuantumForm).map(key=>{
      return timeQuantumForm[key]
    })
  }

  const addTimeQuantum = (newVal?:string[]|null)=>{
    const value: Array<string>|any = newVal || []
    const key = getKey()
    timeQuantumForm[key] = value
    timeQuantumRules[key] = rule
    if(Object.keys(timeQuantumForm).length >= maxNum.value){
      disabled.value = true
    }else{
      disabled.value = false
    }
  }

  const getKey = ():string => {
    const key = `form_${Math.floor(Math.random() * 999)}`
    if(Object.keys(timeQuantumForm).includes(key)){
      return getKey()
    }else{
      return key
    }
  }

  const deleteItem = ($e: boolean, key: string)=>{
    if($e){
      delete timeQuantumForm[key]
      delete timeQuantumRules[key]
      emit('update:modelValue', getParamsArr())
      if(Object.keys(timeQuantumForm).length < maxNum.value){
        disabled.value = false
      }
    }
  }

  const validate = ()=>{
    return new Promise<boolean>((resolve: Function, reject: Function)=>{
      quietTimeQuantumFormRef.value.validate((valid:any) => {
        if (valid) {
          resolve(valid)
        } else {
          reject(false)
        }
      })
    })
  }

  const init = ()=>{
    if(props.modelValue.length){
      props.modelValue.forEach((item:string[])=>{
        addTimeQuantum(item)
      })
    }else{
      addTimeQuantum()
    }
    TimeQuantum.value = defineAsyncComponent(() => import('./TimeQuantum.vue'))
  }

  onMounted(()=>{
    init()
  })

  defineExpose({
    validate
  })

</script>
<style scoped lang="scss">
  .el-form{
    margin-top: 12px;
    .el-form-item{
      
    }

  }
</style>
